import type { TableColumnProps } from '~/components/ProSaasTable/typings'
import type { DeviceApplicationDataItemType } from '../typings'
import type { CallTestResultsDataItemType, CallTestResultsWeekSunsierDataItemType } from './typings'
import { defineComponent, ref, watch, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import dayjs from 'dayjs'
import { ElDialog, ElDescriptions, ElDescriptionsItem, ElMessage } from 'element-plus'
import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import useWebsocket from '~/hooks/useWebsocket'
import { MODAL_NORMAL_WIDTH } from '~/utils/const'
import { handleEnumValue } from '~/utils/util'

export default defineComponent({
  name: 'CallTestResultsModal',
  props: ['detail', 'doClose'],
  setup(props: { detail: DeviceApplicationDataItemType; doClose: () => void }) {
    const store = useStore()
    const callTestData = ref<CallTestResultsDataItemType>()
    const userState = useVuexGetters('user', ['token'])
    const switchLightStrategyState = useVuexGetters('switchLightStrategy', ['taskTypeEnum'])
    const webSocketRef = useWebsocket('/websocket/protocol/hardware', {
      // 初始化webSocket后发送数据
      onopen: handleWebSocketInitMessage,
      // 接收数据回调
      onmessage: handleWebSocketReceiveMessage
    })

    // 初始化 ｜ 重新发送给 websocket 数据
    function handleWebSocketInitMessage() {
      if (!props.detail?.id) {
        props?.doClose()
        return
      }

      // if (!props.detail?.taskStatus) {
      //   ElMessage.error('设备回路未下发任务!')
      //   props?.doClose()
      //   return
      // }
      const params = {
        deviceId: props.detail.deviceId || '',
        commandCode: '',
        // params: {
        //   token: userState.token.value
        // }
        token: userState.token.value
      }

      if (props.detail?.taskType === 1) {
        // 召测周任务
        // params.commandCode = 'D00040'
        params.commandCode = '10039'
      } else if (props.detail?.taskType === 2) {
        // 召测多时段
        // params.commandCode = 'D00041'
        params.commandCode = '10041'
      } else if (props.detail?.taskType === 3) {
        // 召测全天
        // params.commandCode = 'D00042'
        params.commandCode = '10040'
      }

      webSocketRef.value!.send(JSON.stringify(params))
      delete params.token
      store
        .dispatch('deviceApplication/CallTestDeviceApplicationInfo', { ...params, params })
        .then((res) => {
          if (res.success) ElMessage.success('下发成功')
        })
    }

    // 接收webSocketRef返回值
    function handleWebSocketReceiveMessage(res: { data: string }) {
      try {
        callTestData.value = JSON.parse(res.data)
        callTestData.value!.content = JSON.parse(callTestData.value?.content as unknown as string)
      } catch (error) {
        callTestData.value = {}
      }
    }

    watch(
      () => props?.detail?.id,
      () => {
        handleWebSocketInitMessage()
      }
    )

    const columns: TableColumnProps<CallTestResultsWeekSunsierDataItemType>[] = [
      {
        label: '日期',
        prop: 'planDate',
        minWidth: 180
      },
      {
        label: '星期',
        prop: 'weekTime',
        minWidth: 180,
        render: (_, value) => <>{dayjs().day(value!).format('ddd')}</>
      },
      {
        label: '开灯时间',
        prop: 'closeTime',
        minWidth: 180
      },
      {
        label: '关灯时间',
        prop: 'openTime',
        minWidth: 180
      }
    ]

    // 离开前 先断开websocket连接
    onUnmounted(() => {
      webSocketRef.value?.close()
    })

    return () => (
      <ElDialog
        width={MODAL_NORMAL_WIDTH}
        title="召测结果"
        modelValue={!!callTestData.value?.content}
        closeOnClickModal={false} // 点遮罩层不关弹窗
        draggable // 可拖拽
        beforeClose={props?.doClose}
      >
        <ElDescriptions>
          {/* 全天任务展示执行动作 */}
          {props.detail.taskType === 3 ? (
            callTestData.value?.content?.outputCtrArray?.map((item) => (
              <>
                <ElDescriptionsItem label="任务名称">
                  {handleEnumValue(
                    switchLightStrategyState.taskTypeEnum.value,
                    props.detail.taskType!
                  )}
                </ElDescriptionsItem>
                <ElDescriptionsItem label="回路开关">{props.detail.loopName}</ElDescriptionsItem>
                <ElDescriptionsItem label="执行动作">
                  {item?.type === 1 && '开灯'}
                  {item?.type === 2 && '关灯'}
                </ElDescriptionsItem>
              </>
            ))
          ) : (
            <>
              <ElDescriptionsItem label="任务名称">
                {handleEnumValue(
                  switchLightStrategyState.taskTypeEnum.value,
                  props.detail.taskType!
                )}
              </ElDescriptionsItem>
              <ElDescriptionsItem label="回路开关">{props.detail.loopName}</ElDescriptionsItem>
            </>
          )}
        </ElDescriptions>
        {/* 周任务展示表格 */}
        {props.detail.taskType === 1 && (
          <ProSaasTable<CallTestResultsWeekSunsierDataItemType>
            columns={columns}
            rowKey="weekTime"
            data={callTestData.value?.content?.weekTimeArray || []}
            needPagination={false}
          />
        )}
      </ElDialog>
    )
  }
})
